<?php

namespace App\Backend\Controllers;

use App\Backend\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Service\UserService;
use App\Backend\Service\BaoliaopostService;
use Illuminate\Support\Facades\Redis;

/**
 * 爆料
 */
class BaoliaopostController extends BaseController
{
    private $getRules=[
            'img_url'=> 'required',
            'type'=> 'required',
            'sort'=> 'required',
            'status'=> 'required',
    ];
    private $getRulesMessage=[
            'img_url.required'=> '图片地址不能为空',
            'type.required'=> 'banner类型不能为空',
            'sort.required'=> '排序不能为空',
            'status.required'=> '状态不能为空',
    ];
    public $URL_MAP;
    public function __construct(BaoliaopostService $centerService,UserService $userService)
    {
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->repository = $centerService;
        $this->userService=$userService;
        parent::__construct();
    }


    /**
     * 列表
     */
    public function getList(Request $request)
    {

        //dd($request);
        $data=[
            'title'=>$request->input("title"),
            'start_date'=>$request->input("start_date"),
            'end_date'=>$request->input("end_date"),
            'check_status'=>$request->input("check_status"),
            'check_result'=>$request->input("check_result"),
            'channel'=>$request->input("channel"),
        ];
        $this->success($this->repository->getList($request,$data));
    }

    

    /**
     * 添加
     */
    public function add(Request $request)
    {
        $type=$request->json("type");
        if(empty($type)){
            $type=2;
        }
        //die("Sdfs");
        #用户id
        $user_id=$request->json("user_id");
        $avatar="";
        $nickname="";
        if(!empty($user_id) && $user_id>=1000){
           $user_info=$this->userService->update_user($user_id);
           $nickname=$user_info['nickname'];
           $avatar=$user_info['avatar'];
           
        }
        if(empty($user_id)){
            $this->error("用户Id不能为空");
        }

        $purchase=[];
        $purchase_steps=[];
        $purchase_youhuiquan=$request->json("purchase_youhuiquan");
        //dd($purchase_youhuiquan);
        $purchase_huodong=$request->json("purchase_huodong");
        $purchase_jiagou=$request->json("purchase_jiagou");
        $purchase_coudan=$request->json("purchase_coudan");

        if(!empty($purchase_youhuiquan)){
            $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
        }
        if(!empty($purchase_huodong)){
            $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
        }
        if(!empty($purchase_jiagou)){
            $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
        }
        if(!empty($purchase_coudan)){
            $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
        }
        //dd($purchase_steps);
        //佣金比例
        $commission_rate=$request->json("commission_rate");
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate*100;
        //数量
        $quantity=$request->json("quantity",1);
        if(empty($quantity)){
            $quantity=1;
        }
        //单价
        $unit_price=$request->json("unit_price",0);
        if(empty($unit_price)){
            $unit_price=1;
        }
        //下单价
        $final_price=$unit_price*$quantity;
        //佣金金额
        $commission_amount=$request->json("commission_amount");
        //佣金总金额
        $commission_amount_total=$commission_amount*$quantity;

        $category_id=$request->json("category_id");
        $category_name=$request->json("category_name");
        $platform=$request->json("platform");
        #是否是产品的默认值
        $is_product=0;
        //dd($platform);
        $productId=$request->json("product_id");
        if($productId){
            $is_product=1;
        }
        //dd($platform);
        //测试京东
        //$platform='拼多多';
        //$productId='E9L2lYP4BSBHtvaxwfjfHwEH8luiqAiApA_JkqttchhD';
        $product_list=[];
        if(isset($this->URL_MAP[$platform])){
            $url=$this->URL_MAP[$platform];
        }else{
            $url="";
        }
        
        if($url){
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform,$productId,$url);

            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
        }

        $purchase_screenshots=[];
        $purchase_screenshots=$request->json("purchase_screenshots");
        $purchase_screenshots=array_filter($purchase_screenshots);
        $purchase_screenshots=array_unique($purchase_screenshots);
        //dd($purchase_screenshots);

        $image=[];
        $images=$request->json("images");
        $images=array_filter($images);
        $images=array_unique($images);

        $product_unique_id=$request->json("product_unique_id");
        //dd($platform);
        if(empty($product_unique_id)&&$productId){
            $ar=platform_name_product_id($platform,$productId);
            $product_unique_id=$ar['1'];
          
        }
        //dd($product_unique_id);
        $article_id=$request->json("article_id");
        if(empty($article_id)){
            $article_id='-1';
        }
        $article_url="";
        if(!empty($unique_id)){
            $article_url="https://www.smzdm.com/p/{$article_id}";
        }
        #预售时间
        $begin_date=$request->json("begin_date");
        if(empty($begin_date)){
            $begin_date='1970-01-01 00:00:00';
        }
        if(empty($productId)){
            $productId=0;
        }
        $cover=$request->json("cover");
        if(is_array($cover)){
            if(empty($cover)){
                $cover="";
            }else{
                $cover=$cover[0];
            }
        }

        if($begin_date=='0000-00-00 00:00:00'){
            $begin_date='1970-01-01 00:00:00';
        }

        $data=[
            'unique_id'=>generateNum(),
            'article_id'=>$article_id,
            'begin_time'=>$begin_date,
            'is_product'=>$is_product,
            'purchase_steps'=>$purchase_steps,
            'title'=>$request->json("title"),//文章标题
            'platform_name'=>$platform,
            
            'original_brand_name'=>$request->json("original_brand_name"),//商品品牌名称
            'standard_category_name'=>$request->json("standard_category_name"),//商品原始分类名称
            'brand_name'=>$request->json("brand_name"),//品牌名称
            'start_time'=>$request->json("start_time"),
            'article_title'=>$request->json("article_title"),//商品标题
            'end_time'=>$request->json("end_time"),
            'content'=>$request->json("content"),
            'cover'=>$cover,
            'product_id'=>$productId,
            'unit_price'=>$unit_price,
            'quantity'=>$quantity,
            'final_price'=>$final_price,
            'commission_amount_total'=>$commission_amount_total,
            'images'=>$images,
            'purchase_screenshots'=>$purchase_screenshots,
            'category_id'=>$category_id,
            'category_name'=>$category_name,
            'origain_price'=>$request->json("origain_price"),
            'commission_rate'=>$commission_rate,
            'commission_amount'=>$commission_amount,//佣金金额
            'shop_id'=>$request->json("shop_id"),
            'product_unique_id'=>$product_unique_id,
            'product_list'=>$product_list,
            'type'=>$type, //2用户添加数据  3.机器人推动数据
            'publish_time'=>date("Y-m-d H:i:s"),
            'is_expired'=>2,
            'user_id'=>$user_id,
            'avatar'=>$avatar,
            'nickname'=>$nickname,
            'article_url'=>$article_url,

        ];
        if(empty($article_id)){
            $this->error("文章id【article_id】不能为空");

        }
     /*   if(empty($data['article_title'])){
            $this->error("商品标题【article_title】不能为空");

        }*/


        $platform_name=$data['platform_name'];
        //活动，优惠，加购，凑单，下单
        $purchase_steps=$data['purchase_steps'];
        #组装数据
        foreach ($purchase_steps as $k=> &$v) {
            switch ($v['type']) {
                case '1':
                    $v['data-dimension122']="优惠券";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '2':
                    if(isset($v['link'])&&empty($v['link'])){
                        unset($purchase_steps[$k]);
                    }else{
                        $v['data-dimension122']="活动";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                    }
                    
                    break;
                case '3':
                    $v['data-dimension122']="加购";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '4':
                    $v['data-dimension122']="凑单";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                default:
            }


        }
        $link="";
        if(!empty($data['product_list'])){
            $link=$data['product_list'][0]['text'];
        }
        
        $article_title=$data['article_title'];
        if(empty($article_title)){
            $article_title=$data['title'];
        }
        //dd($data['product_list']);
        //加购
        $purchase_steps[]=[
            "data-dimension122"=> "加购",
            "type"=>3,
            "tag_text"=> "下单{$quantity}件-{$article_title}",
            "you_hui_tiao_zhuan_link_end"=> "",
            "huo_dong_time"=> null,
            "platform"=>$platform_name,
            "title"=> "加购",
            "description"=> "下单{$quantity}件-{$article_title}",
            "link"=>$link,

        ];
        //$quantity=1;
        //下单
        if($quantity>1){

            $lastunitPrice = $unit_price-$commission_amount;
            //dd($commission_amount);
            //$shifu=$unit_price*$quantity;
            $lastunitPrice =_round($lastunitPrice);
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "title"=> "下单",
                "type"=> 5,
                "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                "link"=>'',
                "platform"=>'',
            ];
        }else{
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "type"=> 5,
                "title"=> "下单",
                "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                "link"=>'',
                "platform"=>'',
            ];
        }

        //dd($purchase_steps);
        //die("6666");
        $data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        $data['purchase_screenshots'] = json_encode($data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
        
        $data['product_list'] = json_encode($data['product_list'], JSON_UNESCAPED_UNICODE);

        
        //dd("sdfsd");
        $this->success($this->repository->add($request,$data));
        
    }   


     /**
     * 编辑
     */
    public function edit(Request $request)
    {
        $type=$request->json("type");
        if(empty($type)){
            $type=2;
        }
        #用户id
        $user_id=$request->json("user_id");
        $avatar="";
        $nickname="";
        if(!empty($user_id) && $user_id>=1000){
           $user_info=$this->userService->update_user($user_id);
           $nickname=$user_info['nickname'];
           $avatar=$user_info['avatar'];
           
        }
        if(empty($user_id)){
            $this->error("用户Id不能为空");
        }

        $purchase=[];
        $purchase_steps=[];
        $purchase_youhuiquan=$request->json("purchase_youhuiquan");
        //dd($purchase_youhuiquan);
        $purchase_huodong=$request->json("purchase_huodong");
        $purchase_jiagou=$request->json("purchase_jiagou");
        $purchase_coudan=$request->json("purchase_coudan");

        if(!empty($purchase_youhuiquan)){
            $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
        }
        if(!empty($purchase_huodong)){
            $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
        }
        if(!empty($purchase_jiagou)){
            $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
        }
        if(!empty($purchase_coudan)){
            $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
        }
        //dd($purchase_steps);
        //佣金比例
        $commission_rate=$request->json("commission_rate");
        //dd($commission_rate);
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate*100;
        //dd($commission_rate);
        //数量
        $quantity=$request->json("quantity",1);
        if(empty($quantity)){
            $quantity=1;
        }
        //单价
        $unit_price=$request->json("unit_price",0);
        if(empty($unit_price)){
            $unit_price=1;
        }
        //下单价
        $final_price=$unit_price*$quantity;
        //佣金金额
        $commission_amount=$request->json("commission_amount");
        //佣金总金额
        $commission_amount_total=$commission_amount*$quantity;

        $category_id=$request->json("category_id");
        $category_name=$request->json("category_name");
        $platform=$request->json("platform");
        //dd($platform);
        $productId=$request->json("product_id");
        if($productId){
            $is_product=1;
        }
        //dd($platform);
        //测试京东
        //$platform='拼多多';
        //$productId='E9L2lYP4BSBHtvaxwfjfHwEH8luiqAiApA_JkqttchhD';
        $url="";
        $product_list=[];
        if(isset($this->URL_MAP[$platform])){
            $url=$this->URL_MAP[$platform];
        }
        
        if($url){
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform,$productId,$url);

            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
        }

        $purchase_screenshots=[];
        $purchase_screenshots=$request->json("purchase_screenshots");
        $purchase_screenshots=array_filter($purchase_screenshots);
        $purchase_screenshots=array_unique($purchase_screenshots);
        //dd($purchase_screenshots);

        $image=[];
        $images=$request->json("images");
        $images=array_filter($images);
        $images=array_unique($images);

        $product_unique_id=$request->json("product_unique_id");
        if(empty($product_unique_id)&&$productId){
            $ar=explode('_',$productId);
            if(is_array($ar)){
                $product_unique_id=$ar['1'];
            }else{
                $product_unique_id=$productId;
            }

        }
        $article_id=$request->json("article_id");
        if(empty($article_id)){
            $article_id='-1';
        }
        $article_url="";
        if(!empty($unique_id)){
            $article_url="https://www.smzdm.com/p/{$article_id}";
        }
        #预售时间
        $begin_date=$request->json("begin_date");
        if(empty($begin_date)){
            $begin_date='1970-01-01 00:00:00';
        }
        $cover=$request->json("cover");
        if(is_array($cover)){
            if(empty($cover)){
                $cover="";
            }else{
                $cover=$cover[0];
            }
        }

        if($begin_date=='0000-00-00 00:00:00'){
            $begin_date='1970-01-01 00:00:00';
        }
        

        $data=[
            'unique_id'=>$request->input("unique_id"),
            //'article_id'=>$article_id,
            'begin_time'=>$begin_date,
            'is_product'=>$is_product,
            'purchase_steps'=>$purchase_steps,
            'title'=>$request->json("title"),//文章标题
            'platform_name'=>$platform,
            'brand_name'=>$request->json("brand_name"),//品牌名称
            'start_time'=>$request->json("start_time"),
            'article_title'=>$request->json("article_title"),//商品标题
            'end_time'=>$request->json("end_time"),
            'content'=>$request->json("content"),
            'cover'=>$cover,
            'product_id'=>$productId,
            'unit_price'=>$unit_price,
            'quantity'=>$quantity,
            'final_price'=>$final_price,
            'commission_amount_total'=>$commission_amount_total,
            'images'=>$images,
            'purchase_screenshots'=>$purchase_screenshots,
            'category_id'=>$category_id,
            'category_name'=>$category_name,
            'origain_price'=>$request->json("origain_price"),
            'commission_rate'=>$commission_rate,
            'commission_amount'=>$commission_amount,//佣金金额
            'shop_id'=>$request->json("shop_id"),
            'product_unique_id'=>$product_unique_id,
            'product_list'=>$product_list,
            'type'=>$type, //2用户添加数据  3.机器人推动数据
            'publish_time'=>date("Y-m-d H:i:s"),
            'is_expired'=>2,
            'user_id'=>$user_id,
            'avatar'=>$avatar,
            'nickname'=>$nickname,
            'article_url'=>$article_url,

        ];
        
        $unique_id=$data['unique_id'];
        if(empty($unique_id)){
            $this->error('[unique_id]参数错误');
        }


        //dd($data);


        $platform_name=$data['platform_name'];
        //活动，优惠，加购，凑单，下单
        $purchase_steps=$data['purchase_steps'];
        #组装数据
        foreach ($purchase_steps as $k=> &$v) {
            switch ($v['type']) {
                case '1':
                    $v['data-dimension122']="优惠券";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '2':
                    if(isset($v['link'])&&empty($v['link'])){
                        unset($purchase_steps[$k]);
                    }else{
                        $v['data-dimension122']="活动";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                    }
                    
                    break;
                case '3':
                    $v['data-dimension122']="加购";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '4':
                    $v['data-dimension122']="凑单";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                default:
            }


        }
        $link="";
        if(!empty($data['product_list'])){
            $link=$data['product_list'][0]['text'];
        }
        
        $article_title=$data['article_title'];
        if(empty($article_title)){
            $article_title=$data['title'];
        }
        //dd($data['product_list']);
        //加购
        $purchase_steps[]=[
            "data-dimension122"=> "加购",
            "type"=>3,
            "tag_text"=> "下单{$quantity}件-{$article_title}",
            "you_hui_tiao_zhuan_link_end"=> "",
            "huo_dong_time"=> null,
            "platform"=>$platform_name,
            "title"=> "加购",
            "description"=> "下单{$quantity}件-{$article_title}",
            "link"=>$link,

        ];
        //$quantity=1;
        //下单
        if($quantity>1){

            $lastunitPrice = $unit_price-$commission_amount;
            //dd($commission_amount);
            //$shifu=$unit_price*$quantity;
            $lastunitPrice =_round($lastunitPrice);
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "title"=> "下单",
                "type"=> 5,
                "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                "link"=>'',
                "platform"=>'',
            ];
        }else{
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "type"=> 5,
                "title"=> "下单",
                "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                "link"=>'',
                "platform"=>'',
            ];
        }

        //dd($purchase_steps);
        //die("6666");




        //dd($data);
        $data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        $data['purchase_screenshots'] = json_encode($data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
        
        
        $data['product_list'] = json_encode($data['product_list'], JSON_UNESCAPED_UNICODE);



     
        $this->success($this->repository->edit($request,$data,$unique_id));
    }

    // 详情
     public function detail(Request $request)
    {
        $unique_id = $request->input('unique_id');
        if(empty($unique_id)){
            $this->error('参数错误');
        }
        $this->success($this->repository->detail($request,$unique_id));
    }

    /**
     * 删除
     */
    public function del(Request $request)
    {
        $ids = $request->json("unique_id");
        //die("77777");
        if(empty($ids)){
            $this->error('参数错误555');
        }
       // dd($ids);
        $this->success($this->repository->del($ids));
    }



}
